﻿using Nest;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Wicture.DbRESTFul;
using Wicture.EPC.OnlineQueryProxy.Core;
using Wicture.EPC.OnlineQueryProxy.Models.ES;

namespace Wicture.EPC.OnlineQueryProxy.Services.ES
{
    public class ESSearchService : IESSearchService
    {
        public async Task<ISearchResponse<T>> Search<T>(ESQueryRequest queryRequest) where T : class
        {
            ISearchResponse<T> searchResult = null;
            try
            {
                SearchRequest<T> searchRequest = new SearchRequest<T>(queryRequest.Indexs, queryRequest.Types)
                {
                    From = queryRequest.From,
                    Size = queryRequest.Size == 0 ? 50 : queryRequest.Size
                };
                if (queryRequest.QueryContainer != null)
                {
                    searchRequest.Query = queryRequest.QueryContainer;
                }
                if (queryRequest.Aggregation != null)
                {
                    searchRequest.Aggregations = queryRequest.Aggregation;
                }
                if (queryRequest.Sorts != null)
                {
                    searchRequest.Sort = queryRequest.Sorts;
                }
                if (queryRequest.Routing != null)
                {
                    searchRequest.Routing = queryRequest.Routing;
                }
                searchResult = await ESUtil.GetClient().SearchAsync<T>(searchRequest);
            }
            catch (Exception ex)
            {
                LoggerManager.Logger.LogError(ex, "ESSearchService.Search");
            }
            return searchResult;
        }
        public async Task<long> Count<T>(ESQueryRequest queryRequest) where T : class
        {
            long count = 0;
            try
            {
                CountRequest<T> searchRequest = new CountRequest<T>(queryRequest.Indexs, queryRequest.Types);
                if (queryRequest.QueryContainer != null)
                {
                    searchRequest.Query = queryRequest.QueryContainer;
                }
                if (queryRequest.Routing != null && queryRequest.Routing.Count() > 0)
                {
                    searchRequest.Routing = queryRequest.Routing[0];
                }
                var searchResult = await ESUtil.GetClient().CountAsync<T>(searchRequest);
                if (searchResult != null)
                {
                    count = searchResult.Count;
                }
            }
            catch (Exception ex)
            {
                LoggerManager.Logger.LogError(ex, "ESSearchService.Count");
            }
            return count;
        }

    }
}
